package com.doit.demo04;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/*
src = D:\work\于和伟.mp4
dest = D:\work\abc\于和伟.mp4
 */
public class copy {
    public static void main(String[] args) throws IOException {
        File src = new File("D:\\work\\于和伟.mp4");
        File dest = new File("D:\\work\\abc\\于和伟.mp4");

        long start = System.currentTimeMillis();
        copy02(src,dest);
        long end = System.currentTimeMillis();
        System.out.println(end-start);
    }

    //字节复制 40873毫秒
    private static void copy01(File src, File dest) throws IOException {
        FileInputStream in = new FileInputStream(src);
        FileOutputStream out = new FileOutputStream(dest);

        int date = 0;
        while ((date =in.read())!=-1){ //读取一个字节
            out.write(date);    //写入一个字节
        }

        out.close();
        in.close();
    }

    //字节流复制 77毫秒
    private static void copy02(File src, File dest) throws IOException {
        //创建字节流输入对象 读取
        FileInputStream in = new FileInputStream(src);
        //创建字节流输出对象 写入
        FileOutputStream out = new FileOutputStream(dest);

        //循环读写
        int len;
        byte[] bytes = new byte[1024];
        while ((len=in.read(bytes))!=-1){
            out.write(bytes,0,len);
        }

        //关闭资源 先开的后管(行业规矩)
        IO_Close.close(in,out);
    }

    private static void copy03(File src , File dest) {
        FileInputStream in=null;
        FileOutputStream out=null;
        try {
             in = new FileInputStream(src);
             out = new FileOutputStream(dest);

            int len;
            byte[] bytes = new byte[1024];
            while ((len=in.read(bytes))!=-1){
                out.write(bytes,0,len);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {

                try {
                    if(in!=null)
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                        try {if (in!=null)
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
    }
//    private static void copy04(File src , File dest) {
//
//        //不用手动关闭了
//        try (new ){
//            in = new FileInputStream(src);
//            out = new FileOutputStream(dest);
//
//            int len;
//            byte[] bytes = new byte[1024];
//            while ((len = in.read(bytes)) != -1) {
//                out.write(bytes, 0, len);
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
}
